<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\admin;

use App\Model\Admin\Dept;
use Hyperf\DbConnection\Model\Model;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\Http\Message\ResponseInterface;

/**
 * 部门管理.
 */
class DeptController extends Crud
{
    /**
     * @var Dept
     */
    protected Model $model;

    /**
     * 构造函数.
     */
    public function __construct()
    {
        $this->model = new Dept;
        parent::__construct();
    }

    /**
     * 浏览.
     */
    public function index(): ResponseInterface
    {
        return $this->render->render('dept/index');
    }

    /**
     * 插入.
     */
    public function insert(): ResponseInterface
    {
        $request = $this->request;
        $render = $this->render;
        if ($request->isMethod('post')) {
            return parent::insert($request);
        }
        return $render->render('dept/insert');
    }

    /**
     * 更新.
     */
    public function update(): ResponseInterface
    {
        $request = $this->request;
        $render = $this->render;
        if ($request->isMethod('post')) {
            return parent::update($request);
        }
        return $render->render('dept/update');
    }

    public function select_tree()
    {
        $admin = admin();
        $dept_id = $admin['dept_id'];
        if ($dept_id > 1) {
            $where['id'] = $dept_id;
        } else {
            $where['pid'] = 0;
        }
        $data = $this->model::with(['children.children.children'])->where($where)->select(['id', 'pid as parentId', 'name as title'])->get();
        return $this->response->json(['status' => ['code' => 200, 'message' => '获取成功'], 'data' => $data]);
    }
}
